using System;
using Vici.Mvc;

namespace Demo.ViciMvc
{
    [AjaxValidated]
    class EmployeeForm : WebForm
    {
        private readonly Employee _employee;

        [ValidateRequired(Message = "Name is required")]
        [ValidateLength(4, Message="Name is too short")]
        [FormTextBox(Width = 25)]
        public string Name;

        [FormDropDown(KeyMember = "BranchID", ValueMember = "Name", ShowBlank = true, BlankKey = 0, BlankValue = "-Select-", OnChange = "Ajax.UpdateDepartments(this.form, function(html) { $('#DepartmentControl').replaceWith(html); })")]
        public int Branch;

        [FormDropDown(Id="DepartmentControl", KeyMember = "DepartmentID" , ValueMember = "Name", ShowBlank = true, BlankKey = 0, BlankValue = "-Select-")]
        public int Department;

        [ValidateRequired(Message = "Salary is required")]
        [ValidateExpression("Department != 4 || Salary > 30000", Message = "Nah! Impossible for an IT employee to make less than 30,000 !")]
        [FormTextBox(Width = 10, FormatString = "0.00")]
        public decimal? Salary;

        public EmployeeForm()
        {
        }

        public EmployeeForm(Employee employee)
        {
            _employee = employee;
        }

        protected override void OnBind()
        {
            if (Validated)
                return; // our form was posted and validated. We'll redirect anyway, so dropdowns don't need to be bound anymore
                
            Fields["Branch"].DataSource = DataService.GetAllBranches();

            if (Branch > 0)
                Fields["Department"].DataSource = DataService.GetAllDepartmentsForBranch(DataService.LoadBranch(Branch));
        }

        protected override void OnFill()
        {
            Name = _employee.Name;
            Branch = _employee.DepartmentID > 0 ? _employee.Department.BranchID : 0;
            Department = _employee.DepartmentID;
            Salary = _employee.Salary;
        }

        protected override void OnPost(bool validated)
        {
            if (validated)
            {
                _employee.Name = Name;
                _employee.DepartmentID = Department;
                _employee.Salary = Salary;
            }
        }

        // This could be done with a validation attribute, but we'll show this as an example
        protected override bool OnValidateField(string fieldName, object fieldValue, out string errorMessage)
        {
            if (fieldName == "Department" && Department < 1)
            {
                errorMessage = "Department is required";

                return false;
            }

            errorMessage = null;

            return true;
        }
    }
}